package com.kkui.liuxin.controller;

import com.kkui.liuxin.service.MkdirService;
import com.kkui.liuxin.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;


@Controller
@ResponseBody
@Slf4j
@RequestMapping("/api")
public class FileUpload {

    @Resource
    UserService userSevice;
    @Resource
    MkdirService mkdirService;

    /**
     * 检查目录是否有同名文件
     * @param FileName 文件名
     * @param response 响应
     * @return
     */
    @ResponseBody
    @GetMapping("/check")
    public String checkSameName(@RequestParam String FileName,HttpServletResponse response){
        if (mkdirService.isFileName(FileName)) {
            response.setStatus(510);
            return "同目录下有同名文件";
        }
        return "同目录下无同名文件";
    }

    /**
     * 默认路径的文件上传入口
     *
     * @param multipartFile 接收前端文件
     * @param authorization jwt验证
     * @return 文件上传反馈
     * @status: 510
     */
    @ResponseBody
    @PostMapping("/upload")
    public String fileGetDefaultPath(@RequestParam("file") MultipartFile multipartFile
            ,@RequestParam("path") String path,@RequestHeader("authorization") String authorization
            , HttpServletResponse response) {
        if (multipartFile.isEmpty()) {
            return "false";
        }
        //原始文件名
        String fileName = multipartFile.getOriginalFilename();

        int id = userSevice.jwtGetUserId(authorization);

        String sonPath = String.valueOf(id) + File.separator + path.replace("/",File.separator) + File.separator + fileName;
        //判断同目录下是否有同名文件
        if (mkdirService.isFileName(sonPath)) {
            response.setStatus(510);
            return "同目录下有同名文件";
        }

        if (!mkdirService.mkdirFile(sonPath, multipartFile)) {
            response.setStatus(510);
            return "上传失败";
        }

        return "success";
    }
}

